import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from utils.sshops import SSHConnection
from utils.custom_log import log_start
logger = log_start('ServiceOps')


class ServiceOps(PublishCommon):

    def __init__(self, utils):
        self.utils = utils
        super().__init__(utils.app_dict)
        self.utils.format_host_dict()
        self.sshtool = SSHConnection(self.utils.host_dict)

    def npm_ops(self, optype):
        if optype == "restart":
            cmd = "cd %s; pm2 restart all" % (self.deploy_path)
        if optype == "stop":
            # 不能用 以后设计
            # cmd = "cd %s; pm2 delete %s" % (self.deploy_path,self.moudle_name)
            pass
        else:
            cmd = "cd %s; %s" % (self.deploy_path, self.startcmd)
        self.sshtool.exec_shell(cmd)

    def jar_ops(self, optype):
        key_name, key_val = self.utils.cmdb.get_keywords_by_env(
            envname=self.envname.lower())
        encrptval = 'export ' + key_name + '=' + key_val + ";"
        cmd = "cd %s; source /etc/profile; %s ./startup.sh %s" % (
            self.deploy_path, encrptval, optype)
        self.sshtool.exec_shell(cmd)

    def tomcat_ops(self, optype):
        cmd = "cd %s; %s" % (self.deploy_path, self.startcmd)
        self.sshtool.exec_shell(cmd)

    def jnode_ops(self, optype):
        if optype == "stop":
            stopcmd = "pm2 delete all"
            cmd = "cd %s; %s" % (self.deploy_path, stopcmd)
        elif optype == "restart":
            restartcmd = "pm2 restart ./pm2/%s.json" % self.moudle_name
            cmd = "cd %s; %s" % (self.deploy_path, restartcmd)
        else:
            cmd = "cd %s; %s" % (self.deploy_path, self.startcmd)
        self.sshtool.exec_shell(cmd)

    def main_start(self, optype):
        if self.packtype in ['php', 'html', 'vue', 'js']:
            logger.info("静态资源配置完毕")
        else:
            if self.packtype == 'jar':
                self.jar_ops(optype)
            elif self.packtype == 'war':
                self.tomcat_ops(optype)
            elif self.packtype == 'npm':
                self.npm_ops(optype)
            elif self.packtype == 'gnode':
                self.jnode_ops(optype)
            else:
                logger.error('未识别的 packtype')
                exit(500)

    def jarsh_restart(self):
        self.update_java_shell(self.sshtool, self.utils.host_dict)
        self.jar_ops('restart')
        self.check_app(self.sshtool)
        self.sshtool.close_ssh()